package com.nidu.demo.company.executor.command;

import com.alibaba.cola.dto.SingleResponse;
import com.nidu.demo.common.constants.Constants;
import com.nidu.demo.company.ability.CompanyDomainService;
import com.nidu.demo.company.convertor.CompanyConvertor;
import com.nidu.demo.company.dto.CompanyAddCmd;
import com.nidu.demo.company.dto.CompanyCO;
import com.nidu.demo.company.gateway.CompanyGateway;
import com.nidu.demo.company.model.Company;
import com.nidu.demo.dept.gateway.DepartmentGateway;
import com.nidu.demo.dept.model.Department;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 公司创建命令执行器
 *
 * @author auto
 */
@Component
@RequiredArgsConstructor
public class CompanyAddCmdExe {

    private final CompanyGateway gateway;

    private final CompanyDomainService domainService;

    private final CompanyConvertor convertor;

    private final DepartmentGateway departmentGateway;

    public SingleResponse<CompanyCO> execute(CompanyAddCmd cmd) {
        // 1. 转换为领域对象
        Company company = Company.create(cmd.getCompanyName(), cmd.getCompanyAddress(), cmd.getCompanyPhoneNumber(), cmd.getSortOrder());

        // 2. 检查对象是否存在
        domainService.validateDuplicate(company.getCompanyName(), null);

        // 3. 调用网关保存
        Company save = this.createCompanyDepartment(company);

        // 4. 转换为DTO返回
        CompanyCO companyCO = convertor.toClientObject(save);

        return SingleResponse.of(companyCO);
    }

    @Transactional
    private Company createCompanyDepartment(Company company){
        Company save = gateway.create(company);
        Department department = Department.create(save.getCompanyName(), Constants.ROOT_DEPT_CODE, Constants.ROOT_DEPT_ID, save.getId(), save.getCompanyName(), Constants.DEFAULT_DESCRIPTION);
        departmentGateway.create(department);
        return save;
    }
} 